import json

import xlrd


def get_data():
    for i in range(1, table1.nrows):
        # 内容分类
        Content_classification = table1.cell_value(i, 1)  # 内容分类
        classification_list.append(Content_classification)
        # incident列表
        incident = table1.cell_value(i, 2)  # incident
        incident_list.append(incident)
        # 难度值列表
        difficulty = table1.cell_value(i, 3)  # 难度
        difficulty_list.append(difficulty)

    row_num = table1.nrows
    list_4 = []
    type_repeat_list = []

    # 四层,内层为字典，外面套一层list，最后再套一层字典，最后最后再来一层列表
    # 最外面一个大列表，然后一个大字典，里面三个KV对，最后一个KV对的value是一个list，list里面是多个字典，每个字典里固定2个KV对
    for i in range(1, row_num):
        level = difficulty_list[i - 1]  # 难度list
        name = incident_list[i - 1]  # 事件list
        type = classification_list[i - 1]  # 内容分类list

        dict_1 = dict()
        dict_1['name'] = name
        dict_1['level'] = level
        # print(dict_1)

        dict_3 = dict()
        # 记得改type_score
        if type not in type_repeat_list:  # 与之前的类别不同,开一个新list
            list_2 = []
            list_2.append(dict_1)  # 将内部的各个keyword字典装入list中
            dict_3['type'] = type
            #####
            type_score = 0
            for index in range(len(list_2)):
                type_score = list_2[index]['level'] + type_score
            type_score = int(type_score / len(list_2))
            #####
            dict_3['type_score'] = type_score
            dict_3['keyword'] = list_2
            list_4.append(dict_3)
            type_repeat_list.append(type)  # 去重作用
        # else重复了，我沿用上次的list
        # if type in type_repeat_list:
        else:
            dict_else_3 = dict()
            list_else = []
            list_2.append(dict_1)
            # 如果重复了，但是会直接加入到上一行的list中
            # dict_else_3['type'] = type
            # dict_else_3['type_score'] = 1.0
            # dict_else_3['keyword'] = list_2
            # list_4.append(dict_else_3)

    # json_data = json.dumps(list_4, indent=4, separators=(',', ':'), ensure_ascii=False)
    with open("../dict/difficulty_library.pkl", "w+", encoding="utf-8") as f:
        # json_data = json.dumps(list_4, indent=4, separators=(',', ':'), ensure_ascii=False)
        json.dump(list_4, f, indent=4, separators=(',', ':'), ensure_ascii=True)

        # print(json_data)


if __name__ == '__main__':
    workbook = xlrd.open_workbook("../data/Excel_to_be_optimized.xls",encoding_override="utf-8")
    table1 = workbook.sheets()[0]
    nro = table1.nrows
    nco = table1.ncols
    classification_list = []
    incident_list = []
    difficulty_list = []
    result_dict = dict()
    # for i in get_data():
    #     info_json = json.dumps(i, ensure_ascii=False, indent=4, separators=(',', ':'))
    #     print(info_json)
    get_data()
